package com.gpframework.module.controller.module;

import cn.hutool.core.lang.Snowflake;
import cn.hutool.core.util.IdUtil;
import com.alibaba.fastjson.JSONException;
import com.alibaba.fastjson.JSONObject;
import com.aliyuncs.dysmsapi.model.v20170525.SendSmsResponse;
import com.aliyuncs.exceptions.ClientException;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.gpframework.common.config.GpframeworkConfig;
import com.gpframework.common.constant.Constants;
import com.gpframework.common.core.domain.AjaxResult;
import com.gpframework.common.core.domain.entity.SysDept;
import com.gpframework.common.core.domain.entity.SysRole;
import com.gpframework.common.core.domain.entity.SysUser;
import com.gpframework.common.core.redis.RedisCache;
import com.gpframework.common.utils.DateUtils;
import com.gpframework.common.utils.StringUtils;
import com.gpframework.common.utils.aliySms.AliySmsUtils;
import com.gpframework.common.utils.file.FileUploadUtils;
import com.gpframework.common.utils.http.HttpUtils;
import com.gpframework.common.utils.sign.Base64;
import com.gpframework.common.weixin.common.constants.WeiXinConstants;
import com.gpframework.framework.config.ServerConfig;
import com.gpframework.module.common.domain.GpCommonAgreement;
import com.gpframework.module.common.domain.GpCommonFeedback;
import com.gpframework.module.common.domain.GpCommonGuidePage;
import com.gpframework.module.common.domain.GpCommonStartPage;
import com.gpframework.module.common.domain.req.GpCommonAgreementReq;
import com.gpframework.module.common.domain.req.GpCommonGuidePageReq;
import com.gpframework.module.common.domain.req.GpCommonStartPageReq;
import com.gpframework.module.common.domain.vo.GpCommonAgreementVo;
import com.gpframework.module.common.domain.vo.GpCommonGuidePageVo;
import com.gpframework.module.common.domain.vo.GpCommonStartPageVo;
import com.gpframework.module.common.service.IGpCommonAgreementService;
import com.gpframework.module.common.service.IGpCommonFeedbackService;
import com.gpframework.module.common.service.IGpCommonGuidePageService;
import com.gpframework.module.common.service.IGpCommonStartPageService;
import com.gpframework.module.req.common.UploadFileListReq;
import com.gpframework.module.req.common.UploadFileReq;
import com.gpframework.module.service.TokenService;
import com.gpframework.module.system.domain.SysPost;
import com.gpframework.module.system.mapper.*;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.RequiredArgsConstructor;
import org.bouncycastle.jce.provider.BouncyCastleProvider;
import org.checkerframework.checker.units.qual.A;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.CollectionUtils;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.crypto.Cipher;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;
import java.io.IOException;
import java.security.AlgorithmParameters;
import java.security.Security;
import java.sql.Time;
import java.util.*;
import java.util.stream.Collectors;

@Validated
@RestController
@Api(tags = "公共接口")
@RequestMapping(value = "/common")
@RequiredArgsConstructor(onConstructor_ = @Autowired)
public class CommonController<DictService> {

    private static final Logger logger = LoggerFactory.getLogger(CommonController.class);
    /**
     * 上传文件基础虚拟路径
     */
    public static final String USERFILES_BASE_URL = "/userfiles/";

    public static final String USERFILES_VIDEO_BASE_URL = "/videofiles/";

    private final RedisCache redisCache;

    private final IGpCommonStartPageService igpCommonStartPageService;

    private final IGpCommonGuidePageService igpCommonGuidePageService;

    private final IGpCommonAgreementService igpCommonAgreementService;

    private final IGpCommonFeedbackService igpCommonFeedbackService;

    private final TokenService tokenService;

    private final SysDictDataMapper sysDictDataMapper;

    private final SysUserMapper sysUserMapper;

    private final SysPostMapper sysPostMapper;

    private final SysRoleMapper sysRoleMapper;

    private final SysDeptMapper sysDeptMapper;

    private final ServerConfig serverConfig;

    /**
     * id生成工具类
     */
    private final Snowflake idWord = IdUtil.getSnowflake(1, 1);

    //private IDictService dictService;

    /**
     * 发送短信
     *
     * @param mobile
     * @param areaCode
     * @param type     1登录 2绑定
     * @return
     * @throws ClientException
     */
    @ResponseBody
    @ApiOperation(value = "发送短信")
    @RequestMapping(value = "/sendSms", method = RequestMethod.GET)
    public AjaxResult sendSms(@ApiParam(name = "mobile", value = "13800138000", required = true) String mobile,
                              @ApiParam(name = "areaCode", value = "123") String areaCode,
                              @ApiParam(name = "type", value = "1", required = true) String type) throws ClientException {
       /* // 手机号
        String mobile = request.getParameter("mobile");
        String areaCode = request.getParameter("areaCode");
        String type = request.getParameter("type");     // 1登录 2绑定*/
        if (StringUtils.isEmpty(mobile)) {
            return AjaxResult.parameterError();
        }
        // 18888888888作为测试账户不需要发送短信
        if ("18888888888".equals(mobile)) {
            return AjaxResult.success();
        }
        String randomCode = String.valueOf((int) ((Math.random() * 9 + 1) * 100000));
        String key;
        if ("1".equals(type)) {
            //登录
            SendSmsResponse res = AliySmsUtils.sendSms(mobile, randomCode, areaCode);
            if ("OK".equals(res.getCode())) {
                key = "cache_app_login:" + areaCode + mobile;
                redisCache.setCacheObject(key, randomCode);
                redisCache.expire(key, 3000);
                return AjaxResult.success("发送成功");
            } else {
                return AjaxResult.error("发送失败，请稍后重试");
            }
        } else if ("2".equals(type)) {
            //绑定
            SendSmsResponse res = AliySmsUtils.sendSms(mobile, randomCode, areaCode);
            if ("OK".equals(res.getCode())) {
                key = "cache_bind_mobile:" + areaCode + mobile;
                redisCache.setCacheObject(key, randomCode);
                redisCache.expire(key, 3000);
                return AjaxResult.success("发送成功");
            } else {
                return AjaxResult.error("发送失败，请稍后重试");
            }
        }
        return AjaxResult.parameterError();
    }


    /*
        /**
         * 文件上传(绝对路径)
         *
         * @throws FileUploadException
       
    @RequestMapping(value = "fileUpload", method = RequestMethod.POST)
    @ResponseBody
    public AjaxResult  fileUpload(MultipartHttpServletRequest request, HttpServletResponse response) {
        Map<String, Object> j = new HashMap();
        List<String> data = new ArrayList<String>();
        List<MultipartFile> files = null;
        try {
            files = request.getFiles("file");
        } catch (MaxUploadSizeExceededException e) {
             return AjaxResult.parameterError();
            j.put("files", files);
           return AjaxResult.success(j);
        }
        Random random = new Random();
        for (MultipartFile file : files) {
            String fileName = file.getOriginalFilename();
            String suffix = fileName.substring(fileName.lastIndexOf("."), fileName.length());
            String oriName = null;
            String fileUrl = null;
            oriName = DateUtils.getOrderNum() + random.nextInt(10000) + suffix;
            if (suffix.matches("(.JPEG|.jpeg|.JPG|.jpg|.png|.PNG|.GIF|.gif)$")) {
                fileUrl = Global.USERFILES_BASE_URL + "imageUpload/" + DateUtils.getYear() + "/" + DateUtils.getMonth() + "/";
            } else {
                fileUrl = Global.USERFILES_VIDEO_BASE_URL + "fileUpload/" + DateUtils.getYear() + "/" + DateUtils.getMonth() + "/";
            }
            // 转存文件
            FileUtils.createDirectory(Global.getUserfilesBaseDir() + fileUrl);
            try {
                File tempFile = new File(Global.getUserfilesBaseDir() + fileUrl + oriName);
                file.transferTo(tempFile);
            } catch (IllegalStateException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }
            data.add(Global.getConfig("productUrl") + fileUrl + oriName);
        }
        j.put("data", data);
       return AjaxResult.success(j);
    }

/**
	 * 获取access_token
	 *
	 * @param appid
	 *            凭证
	 * @param appsecret
	 *            密钥
     * @param JSCODE
	 *            	登录时获取的 code
	 * @return
	 */
    @ResponseBody
    @RequestMapping(value = "getWxOpenId", method = RequestMethod.GET)
    public AjaxResult getWxloginOpenId(HttpServletRequest request, HttpServletResponse response) {
        String JSCODE = request.getParameter("js_code");
        System.out.println("JSCODE:" + JSCODE);
        HashMap<String, String> map = new HashMap<String, String>();
        String requestUrl = WeiXinConstants.ACCESS_OAUTH3_URL.replace("APPID", WeiXinConstants.APP_ID).replace("APPSECRET", WeiXinConstants.APP_SECRET).replace("JSCODE", JSCODE);
        // String requestUrl = WeiXinConstants.ACCESS_OAUTH3_URL.replace("APPID", "wxb29f58309eb66f82").replace("APPSECRET", "cb250496cd057c302ba82324b48dd012").replace("JSCODE", JSCODE);
        String rspStr = HttpUtils.sendGet(requestUrl, "GET", "utf-8");

        JSONObject jsonObject = JSONObject.parseObject(rspStr);


        // 如果请求成功
        if (null != jsonObject) {
            try {
                map.put("openid", jsonObject.getString("openid"));
                map.put("session_key", jsonObject.getString("session_key"));
            } catch (JSONException e) {
                System.out.println("获取token失败 errcode:{} errmsg:{}" + jsonObject.getIntValue("errcode") + jsonObject.getString("errmsg"));
                // 获取token失败
                logger.error("请求url:{}", requestUrl);
                logger.error("获取token失败 errcode:{} errmsg:{}", jsonObject.getIntValue("errcode"),
                        jsonObject.getString("errmsg"));

            }
        }
        return AjaxResult.success(map);
    }

    /**
     * 获取手机号
     * @param request
     * @param response
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "getWxEntryUserInfo", method = RequestMethod.GET)
    public AjaxResult getWxOpenIdWay(HttpServletRequest request, HttpServletResponse response) {
        Map<String, Object> j = new HashMap();
        // sessionKey
        String sessionKey = request.getParameter("session_key");
        //被加密的秘钥
        String encryptedData = request.getParameter("encryptedData");
        //偏移量
        String iv = request.getParameter("iv");
        if (StringUtils.isNotBlank(sessionKey) && StringUtils.isNotBlank(encryptedData) && StringUtils.isNotBlank(iv)) {
            com.alibaba.fastjson.JSONObject jsonObject = getEncryUserInfo(encryptedData, sessionKey, iv);
            if (jsonObject != null) {
                String mobile = jsonObject.getString("phoneNumber");
                return AjaxResult.success(mobile);
            } else {

                return AjaxResult.error(-4, "获取失败；参数效验异常");
            }
        } else {

            return AjaxResult.error(-2, "获取手机号码失败;参数缺失！");
        }
    }

    /**
     * 绑定账号
     * @param sysUser
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "bindUserInfo", method = RequestMethod.POST)
    public AjaxResult bindUserInfo(@Valid @RequestBody SysUser sysUser) {
        Map<String, Object> j = new HashMap<>();
        // 手机号
        String phone = sysUser.getPhonenumber();
        // openid
        String openid = sysUser.getOpenid();
        if (StringUtils.isBlank(openid)) {
            return AjaxResult.error("缺少必要参数[openid]");
        }
        List<SysUser> sysUserList;
        SysUser user;
        sysUser = new SysUser();
        sysUser.setOpenid(openid);
        sysUserList = sysUserMapper.selectUserList(sysUser);
        if (CollectionUtils.isEmpty(sysUserList)) {
            if (StringUtils.isBlank(phone)) {
                return AjaxResult.error("登录失败，请绑定后再重新登录");
            }
            // 没有openid对应的账号，进行账号绑定
            sysUser = new SysUser();
            sysUser.setPhonenumber(phone);
            sysUserList = sysUserMapper.selectUserList(sysUser);
            if (CollectionUtils.isEmpty(sysUserList)) {
                return AjaxResult.error("系统未录入该用户，请在后台管理系统中录入后再进行绑定");
            }
            user = sysUserList.get(0);
            if (StringUtils.equals(user.getStatus(), "1")) {
                return AjaxResult.error("账号被禁用");
            }
            if (StringUtils.isNotBlank(user.getOpenid())) {
                return AjaxResult.error("当前用户已被绑定，如需换绑请先解绑后再进行绑定");
            }
            user.setOpenid(openid);
            sysUserMapper.updateUser(user);
        } else {
            // 有对应openid的账号，直接登录
            user = sysUserList.get(0);
            if (StringUtils.equals(user.getStatus(), "1")) {
                return AjaxResult.error("账号被禁用");
            }
            /*if (!StringUtils.equals(user.getPhonenumber(), phone)) {
                return AjaxResult.error("手机号不匹配，请检查手机号是否输入错误");
            }*/
        }
        List<SysRole> sysRoles = sysRoleMapper.selectRolesByUserName(user.getUserName());
        List<SysDept> deptList = sysDeptMapper.selectChildrenDeptById(101L);
        /*List<SysPost> sysPostList = sysPostMapper.selectPostsByUserName(user.getUserName());
        if (!CollectionUtils.isEmpty(sysPostList)) {
            String postNames = sysPostList.stream().map(SysPost::getPostName).collect(Collectors.joining(","));
            user.setPostNames(postNames);
            List<String> postCodeList = sysPostList.stream().map(SysPost::getPostCode).collect(Collectors.toList());
            user.setPostCodeList(postCodeList);
        }*/
        user.setRoleList(sysRoles);
        user.setDeptList(deptList);
        Time minStartTime = Time.valueOf("23:59:59");
        Time maxEndTime = Time.valueOf("00:00:00");
        if (CollectionUtils.isEmpty(sysRoles)) {
            minStartTime = Time.valueOf("00:00:00");
            maxEndTime = Time.valueOf("23:59:59");
        } else {
            for (SysRole sysRole : sysRoles) {
                if (sysRole.getQueryStartTime() != null) {
                    if (sysRole.getQueryStartTime().compareTo(minStartTime) < 0) {
                        minStartTime = sysRole.getQueryStartTime();
                    }
                } else {
                    minStartTime = Time.valueOf("00:00:00");
                }
                if (sysRole.getQueryEndTime() != null) {
                    if (sysRole.getQueryEndTime().compareTo(maxEndTime) > 0) {
                        maxEndTime = sysRole.getQueryEndTime();
                    }
                } else {
                    maxEndTime = Time.valueOf("23:59:59");
                }
            }
        }
        Time now = Time.valueOf(DateUtils.parseDateToStr("HH:mm:ss", new Date()));
        if (now.compareTo(minStartTime) <= 0 || now.compareTo(maxEndTime) >= 0) {
            return AjaxResult.error("当前账户不在登录时间段内，无法进行登录");
        }
        return AjaxResult.success(user);
    }

    /**
     * 解绑账号
     * @param sysUser
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "unBindUserInfo", method = RequestMethod.POST)
    public AjaxResult unBindUserInfo(@Valid @RequestBody SysUser sysUser) {
        // 用户id
        Long userId = sysUser.getUserId();
        if (userId == null) {
            return AjaxResult.error("缺少必要参数[userId]");
        }
        SysUser user = sysUserMapper.selectUserById(userId);
        if (user == null) {
            return AjaxResult.error("找不到用户");
        }
        sysUserMapper.unBind(userId);
        return AjaxResult.success("解绑成功");
    }

    /*
     * 用户获取信息解密
     * encryptedData需要解密的数值
     * */
    public static com.alibaba.fastjson.JSONObject getEncryUserInfo(String encryptedData, String sessionKey, String iv) {
        // 被加密的数据
        byte[] dataByte = com.gpframework.common.utils.sign.Base64.decode(encryptedData);
        // 加密秘钥
        byte[] keyByte = com.gpframework.common.utils.sign.Base64.decode(sessionKey);
        // 偏移量
        byte[] ivByte = Base64.decode(iv);
        try {
            // 如果密钥不足16位，那么就补足.  这个if 中的内容很重要
            int base = 16;
            if (keyByte.length % base != 0) {
                int groups = keyByte.length / base + (keyByte.length % base != 0 ? 1 : 0);
                byte[] temp = new byte[groups * base];
                Arrays.fill(temp, (byte) 0);
                System.arraycopy(keyByte, 0, temp, 0, keyByte.length);
                keyByte = temp;
            }
            // 初始化
            Security.addProvider(new BouncyCastleProvider());
            Cipher cipher = Cipher.getInstance("AES/CBC/PKCS7Padding", "BC");
            SecretKeySpec spec = new SecretKeySpec(keyByte, "AES");
            AlgorithmParameters parameters = AlgorithmParameters.getInstance("AES");
            parameters.init(new IvParameterSpec(ivByte));
            cipher.init(Cipher.DECRYPT_MODE, spec, parameters);// 初始化
            byte[] resultByte = cipher.doFinal(dataByte);
            if (null != resultByte && resultByte.length > 0) {
                String result = new String(resultByte, "UTF-8");
                return com.alibaba.fastjson.JSONObject.parseObject(result);
            }
        } catch (Exception e) {
            Logger logger = LoggerFactory.getLogger(CommonController.class);
            logger.error(e.getMessage());
        }
        return null;
    }


    /**
     * 2.保存微信用户信息
     *
     * @throws IOException
     */


    /**
     * 启动页
     *
     * @param request
     * @param response
     * @return
     */
    @ApiOperation("启动页")
    @RequestMapping(value = "/start", method = RequestMethod.GET)
    public AjaxResult startPage(HttpServletRequest request, HttpServletResponse response) {
        Map<String, Object> j = new HashMap();

        GpCommonStartPageReq gpCommonStartPageReq = new GpCommonStartPageReq();
        gpCommonStartPageReq.setEnableFlag("1");
        QueryWrapper<GpCommonStartPage> lqw = new QueryWrapper();
        gpCommonStartPageReq.generatorQuery(lqw, true);
        List<GpCommonStartPageVo> gpCommonStartPageList = igpCommonStartPageService.listVo(lqw);

        j.put("gpCommonStartPageList", gpCommonStartPageList);
        return AjaxResult.success(j);
    }

    /**
     * 引导页
     *
     * @param request
     * @param response
     * @return
     */
    @ApiOperation("引导页")
    @RequestMapping(value = "/guide", method = RequestMethod.GET)
    public AjaxResult guidePage(HttpServletRequest request, HttpServletResponse response) {
        Map<String, Object> j = new HashMap();

        GpCommonGuidePageReq gpCommonGuidePageReq = new GpCommonGuidePageReq();
        gpCommonGuidePageReq.setEnableFlag("1");
        gpCommonGuidePageReq.setDelStatus(0);
        QueryWrapper<GpCommonGuidePage> lqw = new QueryWrapper();
        gpCommonGuidePageReq.generatorQuery(lqw, true);
        List<GpCommonGuidePageVo> gpCommonGuidePageList = igpCommonGuidePageService.listVo(lqw);
        j.put("gpCommonGuidePageList", gpCommonGuidePageList);
        return AjaxResult.success(j);
    }

    /**
     * 关于我们
     *
     * @param request
     * @param response
     * @return
     */
    @ApiOperation("关于我们")
    @RequestMapping(value = "/aboutUs", method = RequestMethod.GET)
    public AjaxResult aboutUs(HttpServletRequest request, HttpServletResponse response) {
        Map<String, Object> j = new HashMap();
        List<GpCommonAgreement> gpCommonAgreementList = igpCommonAgreementService.list();
        j.put("gpCommonAgreementList", gpCommonAgreementList);
        return AjaxResult.success(j);
    }

    /**
     * 关于我们详情
     *
     * @param request
     * @param response
     * @return
     */
    @ApiOperation("关于我们详情")
    @RequestMapping(value = "/aboutUsDetails", method = RequestMethod.GET)
    public AjaxResult aboutUsDetails(HttpServletRequest request, HttpServletResponse response) {
        Map<String, Object> j = new HashMap();
        String mode = request.getParameter("mode");
        if (StringUtils.isNotBlank(mode)) {
            GpCommonAgreementReq gpCommonAgreementReq = new GpCommonAgreementReq();
            gpCommonAgreementReq.setMode(mode);
            QueryWrapper<GpCommonAgreement> lqw = new QueryWrapper();
            gpCommonAgreementReq.generatorQuery(lqw, true);
            List<GpCommonAgreementVo> gpCommonAgreementList = igpCommonAgreementService.listVo(lqw);

            if (CollectionUtils.isEmpty(gpCommonAgreementList)) {
                return AjaxResult.error("协议不存在");
            }
            GpCommonAgreementVo gpCommonAgreementVo = new GpCommonAgreementVo();
            gpCommonAgreementVo = gpCommonAgreementList.get(0);
            j.put("gpCommonAgreement", gpCommonAgreementVo);
        } else {
            return AjaxResult.parameterError();
        }
        return AjaxResult.success(j);
    }

    /**
     * 反馈意见
     *
     * @param gpCommonFeedbackReq
     * @param response
     * @return
     */
    @ApiOperation("反馈意见")
    @RequestMapping(value = "/feedback", method = RequestMethod.POST)
    public AjaxResult feedback(@RequestBody GpCommonFeedback gpCommonFeedbackReq, HttpServletResponse response) {
        Map<String, Object> j = new HashMap();
        Long memberId = gpCommonFeedbackReq.getMemberId();
        String content = gpCommonFeedbackReq.getContent();
        if (memberId != null && StringUtils.isNotBlank(content)) {
            GpCommonFeedback gpCommonFeedback = new GpCommonFeedback();
            gpCommonFeedback.setMemberId(memberId);
            gpCommonFeedback.setContent(content);
            igpCommonFeedbackService.save(gpCommonFeedback);
        } else {
            return AjaxResult.parameterError();
        }
        return AjaxResult.success(j);
    }

/**
 * 单文件上传
 * @param req
 * @param response
 * @return
 *//*

    @ResponseBody
    @RequestMapping(value = "/uploadFile", method = RequestMethod.POST)
    public AjaxResult  uploadFile(@Valid UploadFileReq req, HttpServletResponse response)
    {

        Map<String, Object> j = new HashMap();
        String type = req.getType();
        MultipartFile file = req.getFile();
        Random random = new Random();
        String fileName = file.getOriginalFilename();
        String suffix = fileName.substring(fileName.lastIndexOf("."), fileName.length());
        String oriName = null;
        String fileUrl = null;
        oriName = DateUtils.getOrderNum() + random.nextInt(10000) + suffix;
        if ("1".equals(type)) {
            fileUrl = Global.USERFILES_BASE_URL + "imageUpload/" + DateUtils.getYear() + "/" + DateUtils.getMonth() + "/";
        } else {
            fileUrl = Global.USERFILES_VIDEO_BASE_URL + "fileUpload/" + DateUtils.getYear() + "/" + DateUtils.getMonth() + "/";
        }
        // 转存文件
        FileUtils.createDirectory(Global.getUserfilesBaseDir() + fileUrl);
        try {
            File tempFile = new File(Global.getUserfilesBaseDir() + fileUrl + oriName);
            file.transferTo(tempFile);
        } catch (IllegalStateException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        Map<String,Object> result = new HashMap<>();
        result.put("fileName", oriName);
        result.put("url", Global.getConfig("productUrl") + fileUrl + oriName);
        j.put("data", result);
       return AjaxResult.success(j);
    }

    */

    /**
     * 多文件上传
     *
     * @param req
     * @return
     *//*

    @ResponseBody
    @RequestMapping(value = "/uploadFileList", method = RequestMethod.POST)
    public AjaxResult  uploadFileList(@Valid UploadFileListReq req, HttpServletResponse response)
    {
        Map<String, Object> j = new HashMap();
        String type = req.getType();
        List<MultipartFile> files = req.getFiles();
        Random random = new Random();
        List<Map<String,Object>> list = new ArrayList<>();
        for (MultipartFile file : files) {
            String fileName = file.getOriginalFilename();
            String suffix = fileName.substring(fileName.lastIndexOf("."), fileName.length());
            String oriName = null;
            String fileUrl = null;
            oriName = DateUtils.getOrderNum() + random.nextInt(10000) + suffix;
            if ("1".equals(type)) {
                fileUrl = Global.USERFILES_BASE_URL + "imageUpload/" + DateUtils.getYear() + "/" + DateUtils.getMonth() + "/";
            } else {
                fileUrl = Global.USERFILES_VIDEO_BASE_URL + "fileUpload/" + DateUtils.getYear() + "/" + DateUtils.getMonth() + "/";
            }
            // 转存文件
            FileUtils.createDirectory(Global.getUserfilesBaseDir() + fileUrl);
            try {
                File tempFile = new File(Global.getUserfilesBaseDir() + fileUrl + oriName);
                file.transferTo(tempFile);
            } catch (IllegalStateException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }
            Map<String, Object> result = new HashMap<>();
            result.put("fileName", oriName);
            result.put("url", Global.getConfig("productUrl") + fileUrl + oriName);
            list.add(result);
        }
        j.put("list", list);
       return AjaxResult.success(j);
    }
*/
    @ApiOperation(value = "多文件上传")
    @PostMapping("/uploadFileList")
    public AjaxResult uploadFileList(@Valid UploadFileListReq req) {
        List<Map<String, Object>> list = new ArrayList<>();
        String type = req.getType();
        for (MultipartFile file : req.getFiles()) {
            try {
                // 上传文件路径
                String filePath = GpframeworkConfig.getUploadPath();
                if (Constants.UPLOAD_FILE_TYPE_HEADIMAGE.equals(type)) {
                    filePath = filePath + "/headimage";
                } else if (Constants.UPLOAD_FILE_TYPE_PHOTO.equals(type)) {
                    filePath = filePath + "/photowall";
                } else if (Constants.UPLOAD_FILE_TYPE_VOICE.equals(type)) {
                    filePath = filePath + "/voice";
                }
                // 上传并返回新文件名称
                String fileName = FileUploadUtils.upload(filePath, file);
                String url = ServerConfig.getUrl() + fileName;
                Map<String, Object> result = new HashMap<>();
                result.put("fileName", fileName.replaceAll("\\\\", ""));
                result.put("url", url.replaceAll("\\\\", ""));
                list.add(result);
            } catch (IOException e) {
                return AjaxResult.error(e.getMessage());
            }
        }
        return AjaxResult.success(list);
    }

    /**
     * 通用上传请求
     */
    @PostMapping("/upload")
    public AjaxResult uploadFile(MultipartFile file) throws Exception {
        try {
            // 上传文件路径
            String filePath = GpframeworkConfig.getUploadPath();
            // 上传并返回新文件名称
            String fileName = FileUploadUtils.upload(filePath, file);
            String url = serverConfig.getUrl() + fileName;
            AjaxResult ajax = AjaxResult.success();
            Map<String, Object> result = new HashMap<>();
            result.put("fileName", fileName);
            result.put("url", url);
            ajax.setData(result);
            return ajax;
        } catch (Exception e) {
            return AjaxResult.error(e.getMessage());
        }
    }

    @ApiOperation(value = "单文件上传")
    @PostMapping("/fileUpload")
    public AjaxResult uploadFile(@Valid UploadFileReq req) {
        String type = req.getType();
        try {
            // 上传文件路径
            String filePath = GpframeworkConfig.getUploadPath();
            if (Constants.UPLOAD_FILE_TYPE_HEADIMAGE.equals(type)) {
                filePath = filePath + "/headimage";
            } else if (Constants.UPLOAD_FILE_TYPE_PHOTO.equals(type)) {
                filePath = filePath + "/photowall";
            } else if (Constants.UPLOAD_FILE_TYPE_VOICE.equals(type)) {
                filePath = filePath + "/voice";
            }
            // 上传并返回新文件名称
            String fileName = FileUploadUtils.upload(filePath, req.getFile());
            String url = ServerConfig.getUrl() + fileName;
            AjaxResult ajax = AjaxResult.success();
            Map<String, Object> result = new HashMap<>();
            result.put("fileName", fileName.replaceAll("\\\\", ""));
            result.put("url", url.replaceAll("\\\\", ""));
            ajax.setData(result);
            return ajax;
        } catch (Exception e) {
            return AjaxResult.error(e.getMessage());
        }
    }

    /*@ApiOperation(value = "单文件上传(OSS测试)")
    @PostMapping("/fileUploadTest")
    public AjaxResult fileUploadTest(@Valid UploadFileReq req) {
        String type = req.getType();
        File file = req.getFileTest();
        try {
            // 上传文件路径
            String filePath = GpframeworkConfig.getUploadPath();
            String catalog = "/image";
            if (Constants.UPLOAD_FILE_TYPE_HEADIMAGE.equals(type)) {
                catalog = "/headimage";
            } else if (Constants.UPLOAD_FILE_TYPE_PHOTO.equals(type)) {
                catalog = "/photowall";
            } else if (Constants.UPLOAD_FILE_TYPE_VOICE.equals(type)) {
                catalog = "/voice";
            }
            filePath += catalog;
            // 上传并返回新文件名称
            String fileName = OSS.uploadTest(catalog, file);
            String url = ServerConfig.getUrl() + fileName;
            AjaxResult ajax = AjaxResult.success();
            Map<String, Object> result = new HashMap<>();
            result.put("fileName", fileName.replaceAll("\\\\", ""));
            result.put("url", url.replaceAll("\\\\", ""));
            ajax.setData(result);
            return ajax;
        } catch (Exception e) {
            return AjaxResult.error(e.getMessage());
        }
    }
*/

}
